import React, { Component } from 'react'
import PureRenderMixin from 'react-addons-pure-render-mixin'

import HomeList from '../../../components/HomeList'
import LoadMore from '../../../components/LoadMore'
import { getHomeListData } from '../../../fetch/home/home'

import './style.less'

class List extends Component {
  constructor(props) {
    super(props);
    this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this);
    this.state = {
      data: [],
      hasMore: true,
      isLoadingMore: false,
      page: 1 // 下一页的页码 0代表第一页
    }
  }

  componentDidMount() {
    this.loadPageData()
  }

  // 加载第一页数据
  loadPageData() {
    const cityName = this.props.cityName;
    const result = getHomeListData(cityName, 0);
    this.handleResult(result);
  }

  // 加载更多
  loadMoreData() {
    this.setState({
      isLoadingMore: true
    });
    const cityName = this.props.cityName;
    const result = getHomeListData(cityName, this.state.page);
    this.handleResult(result);
  }

  // 结果处理函数
  handleResult(result) {
    result.then(res => {
      return res.json()
    }).then(json => {
      const hasMore = json.hasMore;
      const data = json.data;
      this.setState({
        hasMore: hasMore,
        data: this.state.data.concat(data),
        isLoadingMore: false
      })
    }).catch(ex => {
      if(__DEV__) {
        console.error('获取猜你喜欢数据出现异常');
      }
    })
  }

  render() {
    return (
      <div>
        <h2 className="home-list-title">猜你喜欢</h2>
        {
          this.state.data.length
          ? <HomeList data={this.state.data}/>
          : <div>加载中...</div>
        }
        {
          this.state.hasMore
          ? <LoadMore isLoadingMore={this.state.isLoadingMore} loadMore={this.loadMoreData.bind(this)}/>
          : ''
        }
      </div>
    )
  }
}

export default List
